package com.example.update.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Service {
    public static void main(String[] args) throws IOException {
        Contacts.Builder contactsBuilder = Contacts.newBuilder();
        // 读取本地已存在的 contacts.bin，反序列化出通讯录对象
        try {
            contactsBuilder.mergeFrom(
                    new FileInputStream("src/main/java/com/example/update/contacts.bin"));
        } catch (FileNotFoundException e) {
            System.out.println("contacts.bin not find, create new file");
        }

        // 向通讯录中新增一个联系人
        contactsBuilder.addContacts(addPeopleInfo());

        // 序列化通讯录，将结果写入文件中
        FileOutputStream outputStream = new FileOutputStream(
                "src/main/java/com/example/update/contacts.bin");
        contactsBuilder.build().writeTo(outputStream);
        outputStream.close();
    }

    private static PeopleInfo addPeopleInfo() {
        PeopleInfo.Builder builder = PeopleInfo.newBuilder();
        Scanner scanner = new Scanner(System.in);
        System.out.println("--------------新增联系人-------------");
        System.out.print("请输入联系人姓名：");
        String name = scanner.nextLine();
        builder.setName(name);

//        System.out.print("请输入联系人年龄：");
//        int age = scanner.nextInt();
//        scanner.nextLine();
//        builder.setAge(age);

        System.out.print("请输入联系人生日：");
        int birthday = scanner.nextInt();
        scanner.nextLine();
        builder.setBirthday(birthday);

        for (int i = 0;; i++) {
            System.out.print("请输入联系人电话" + (i+1) + "(只输⼊回⻋完成电话新增): ");
            String number = scanner.nextLine();
            if (number.isEmpty()) {
                break;
            }
            PeopleInfo.Phone.Builder phoneBuilder = PeopleInfo.Phone.newBuilder();
            phoneBuilder.setNumber(number);
            builder.addPhone(phoneBuilder);
        }

        System.out.println("-----------添加联系人结束-------------");
        return builder.build();
    }
}
